package com.tedu.weibo.controller;

import com.tedu.weibo.mapper.WeiboMapper;
import com.tedu.weibo.pojo.dto.WeiboDTO;
import com.tedu.weibo.pojo.entity.User;
import com.tedu.weibo.pojo.entity.Weibo;
import com.tedu.weibo.pojo.vo.WeiboDetailVO;
import com.tedu.weibo.pojo.vo.WeiboIndexVO;
import com.tedu.weibo.result.JsonResult;
import com.tedu.weibo.result.Status;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/v1/weibo")
@Api(tags = "微博模块")
@Validated//对于方法上不是dto形式的验证
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;
    private RedisTemplate<String, Object> redisTemplate ;

    @ApiOperation(value = "发布微博")
    @PostMapping("/insert")
    public JsonResult insert(@RequestBody WeiboDTO weiboDTO,@ApiIgnore HttpSession session){
        System.out.println("插入微博");
        System.out.println(weiboDTO);
        User user = (User) session.getAttribute("user");
        if (user == null){
            return new JsonResult(Status.NOT_LOGIN);
        }
        Weibo weibo = new Weibo();
        weibo.setUserId(user.getId());
        weibo.setContent(weiboDTO.getContent());
        weibo.setCreated(new Date());
        weiboMapper.insert(weibo);

        return JsonResult.success();
    }
    @ApiOperation(value = "获取首页微博")
    @GetMapping("/selectIndex")
    public JsonResult selectIndex(){
        ValueOperations ops = redisTemplate.opsForValue();
        List<WeiboIndexVO> list = (List<WeiboIndexVO>) ops.get("weiboList");
        if (list == null){
            list = weiboMapper.selectWeiboAll();
            ops.set("weiboList",list);
        }
        return JsonResult.success(list);
    }

    @ApiOperation(value = "获取微博详情")
    @ApiImplicitParam(name = "id",value = "微博id",required = true,example = "10",dataType = "int")
    @GetMapping("/selectById")
    public JsonResult selectById(@Range(min = 1,max = 999999,message = "微博id不合法") @RequestParam Integer id){
        if(id==null||id<0){
            throw new RuntimeException("微博id不合法");
        }
        return JsonResult.success(weiboMapper.selectWeiboById(id));
    }

}
